package com.lhs.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feign.file.FileFeignClient;
import com.lhs.DTO.user.UserLoginDTO;
import com.lhs.DTO.user.UserRegisterDTO;
import com.lhs.mapper.UserMapper;
import com.lhs.mapper.User_PointMapper;
import com.lhs.mapper.Vip_RecordMapper;
import com.lhs.Page.PageParam;
import com.lhs.Page.PageResult;
import com.lhs.Page.PageUtil;
import com.lhs.Result.Result;
import com.lhs.Result.ResultCode;
import com.lhs.service.UserService;
import com.lhs.VO.user.UserInfoVO;
import com.lhs.VO.user.UserLoginVO;
import com.lhs.VO.user.vipVO;
import com.lhs.entity.user.User;
import com.lhs.entity.user.User_point;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    final int USER_POINT_DEFAULT_VALUE = 100;


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private User_PointMapper user_PointMapper;

    @Autowired
    private Vip_RecordServiceimpl vip_RecordServiceimpl;

    @Autowired
    private Vip_RecordMapper vip_RecordMapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        // 参数校验
        if (StringUtils.isEmpty(userLoginDTO.getUsername()) || StringUtils.isEmpty(userLoginDTO.getPassword())) {
            return Result.error("用户名或密码不能为空");
        }
        try {
            // 1. 验证用户名和密码
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", userLoginDTO.getUsername());
            // 注意：实际项目中应使用加盐哈希存储密码，此处仅为示例
            queryWrapper.eq("password", SaSecureUtil.sha256(userLoginDTO.getPassword()));
            User user = userMapper.selectOne(queryWrapper);
            if (user == null) {
                return Result.error("用户名或密码错误");
            }

            // 2. 生成认证token
            StpUtil.login(user.getId());
            String token = StpUtil.getTokenInfo().getTokenValue();

            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setUserId(user.getId());
            userLoginVO.setNickname(user.getNickname());
            userLoginVO.setToken(token);

            return Result.success("登录成功", userLoginVO);
        } catch (Exception e) {
            // 记录异常日志（可根据实际情况替换为具体日志框架）
            return Result.error("系统异常，请稍后再试" + e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result register(UserRegisterDTO userRegisterDTO) {
        // 1. 参数校验
        if (StringUtils.isEmpty(userRegisterDTO.getUsername()) || StringUtils.isEmpty(userRegisterDTO.getPassword())
                || StringUtils.isEmpty(userRegisterDTO.getNickname()) || StringUtils.isEmpty(userRegisterDTO.getEmail())) {
            return Result.error("参数不能为空");
        }
        // 2. 验证用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userRegisterDTO.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return Result.error("用户名已存在");
        }
        // 3. 验证邮箱格式
        String email = userRegisterDTO.getEmail();
        if (!isValidEmail(email)) {
            return Result.error("邮箱格式不正确");
        }

// 4. 验证邮箱是否已存在
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return Result.error("邮箱已存在");
        }

        // 4. 创建用户
        user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPassword(SaSecureUtil.sha256(userRegisterDTO.getPassword()));
        user.setNickname(userRegisterDTO.getNickname());
        user.setEmail(userRegisterDTO.getEmail());

        // 先插入用户信息
        boolean result = userMapper.insert(user) > 0;
        if (result) {
            // 用户插入成功后，再创建积分记录
            User_point userPoint = new User_point();
            userPoint.setUserId(user.getId()); // 此时user.getId()有值
            userPoint.setExp(USER_POINT_DEFAULT_VALUE);
            userPoint.setCurrentPoint(USER_POINT_DEFAULT_VALUE);
            user_PointMapper.insert(userPoint);

            return Result.success("注册成功");
        } else {
            return Result.error("注册失败");
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<UserInfoVO> getUserById() {
        // Sa-Token 会自动判断是否登录，未登录则抛出异常
        Long userId = StpUtil.getLoginIdAsLong();
        return buildUserInfoVO(userId);
    }

    // 根据ID获取用户信息
    @Override
    public Result<UserInfoVO> getUserInfoById(Long userId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            return Result.error(ResultCode.PARAM_ERROR);
        }
        return buildUserInfoVO(userId);

    }

    @Override
    public Map<Long, UserInfoVO> getUserInfoBatch(List<Long> userIds) {
        List<User> users = userMapper.selectBatchIds(userIds);
        return users.stream().collect(Collectors.toMap(
                User::getId,
                user -> {
                    UserInfoVO vo = new UserInfoVO();
                    vo.setUserId(user.getId());
                    vo.setNickname(user.getNickname());
                    vo.setAvatar(user.getAvatar());
                    return vo;
                }
        ));
    }

    // 更新用户头像
 @Override
public Result updateAvatar(MultipartFile file) {
    if (file == null || file.isEmpty()) {
        return Result.error("文件不能为空");
    }

    try {
        fileFeignClient.upload(file);
        return Result.success("头像更新成功");
    } catch (Exception e) {
        return Result.error("头像更新失败");
    }
}


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<UserInfoVO> updateUserInfo(User user) {
        // 参数校验
        if (user == null) {
            return Result.error("用户信息不能为空");
        }

        try {
            // 完善Sa-Token登录状态检查
            if (!StpUtil.isLogin()) {
                return Result.error("用户未登录");
            }
            Long userId = StpUtil.getLoginIdAsLong();
            user.setId(userId);
            boolean result = userMapper.updateById(user) > 0;
            if (result) {
                return getUserById();
            } else {
                return Result.error("更新用户信息失败");
            }
        } catch (Exception e) {
            return Result.error("更新用户信息异常：" + e.getMessage());
        }
    }


    // 获取所有用户信息
    @Override
    public Result<PageResult<User>> getAllUserInfo(PageParam pageParam) {
        // 参数校验
        if (pageParam == null) {
            return Result.error("分页参数不能为空");
        }

        try {
            // 构建查询条件
            QueryWrapper<User> wrapper = new QueryWrapper<>();

            // 使用PageParam构建分页对象
            IPage<User> pageUser = PageUtil.selectPage(userMapper, pageParam, wrapper);

            return Result.success(PageResult.of(pageUser));
        } catch (Exception e) {
            return Result.error("查询用户信息失败: " + e.getMessage());
        }
    }

    // 管理员更新用户信息
    @Override
    public Result updateUserInfo_Admin(Long userId,User user) {
        if (user == null) {
            return Result.error("用户信息不能为空");
        }

        try {
            user.setId(userId);
            boolean result = userMapper.updateById(user) > 0;
            if (result) {
                return Result.success("更新用户信息成功");
            } else {
                return Result.error("更新用户信息失败");
            }
        } catch (Exception e) {
            // 记录异常日志
            log.error("更新用户信息失败，用户ID: {}," + user.getId() + " 错误信息: {}" + e.getMessage());
            return Result.error("更新用户信息失败");
        }
    }


    private Result<UserInfoVO> buildUserInfoVO(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        User_point userPoint = user_PointMapper.selectByUserId(userId);
        if (userPoint == null) {
            return Result.error("用户积分信息不存在");
        }

        Result<vipVO> vipRecordResult = vip_RecordServiceimpl.getVipRecord(userId);
        vipVO vipData = vipRecordResult.getData();

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUserId(user.getId());
        userInfoVO.setNickname(user.getNickname());
        userInfoVO.setAvatar(user.getAvatar());
        userInfoVO.setPoint(userPoint.getCurrentPoint());
        userInfoVO.setVipLevel(vipData.getVipLevel());
        userInfoVO.setVipExpire(vipData.getVipExpire());

        return Result.success(userInfoVO);
    }
    /**
     * 验证邮箱格式是否正确
     *
     * @param email 邮箱地址
     * @return 格式是否正确
     */
    private boolean isValidEmail(String email) {
        if (email == null || email.isEmpty()) {
            return false;
        }

        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return email.matches(emailRegex);
    }


}
